<template>
<view>
<!-- <view class='waitpay-warp'>
  <view class='waitpay-pic fl'>
    <image src='../../img/wallet_icon.png'></image>
  </view>
  <view class='fl'>
    <view class='waitpay'>
      <text>等待买家付款</text>
    </view>
  </view>
</view> -->
<view class="consignee">
   <view class="con-address fl">
      <image src="/static/remao_shop/img/dress_icon.png"></image>
   </view>
   <view class="con-name">
      <text decode="true">{{orderDetailList.ship_name}}&ensp;&ensp;&ensp;{{orderDetailList.ship_mobile}}\n{{orderDetailList.ship_addr}}</text>
   </view>
</view>
<view v-for="(item, index) in orderDetailList.item" :key="index" class="popup-warp">
   <view class="popup-pic fl">
      <image :src="item.pic" v-if="iskan != 1"></image>
      <image :src="item.img" v-if="iskan == 1"></image>
   </view>
   <view class="pop-warp fr">
      <view class="pop-title">
         <text>{{item.name}}</text>
      </view>
      <view class="pop-spec">
         <text>{{item.pdt_desc}}</text>
      </view>
      <view class="pop-current">
         <text>￥</text>
         <text v-if="iskan != 1">{{item.original_price}}</text>
         <text v-if="iskan == 1">{{item.goods_total}}</text>
      </view>
      <view class="pop-repertory fr">
         <text v-if="iskan != 1">x{{item.nums}}</text>
         <text v-if="iskan == 1">x{{item.num}}</text>
      </view>
   </view>
</view>
<view class="needpay-warp">
   <view class="needpay fr">
      <text>合计：</text>
      <view class="paycount">
         <text>￥</text>
         <text v-if="iskan != 1">{{orderDetailList.order_amount}}</text>
         <text v-if="iskan == 1">{{orderDetailList.item[0].goods_total}}</text>
      </view>
   </view>
</view>
<view class="order-bot">
   <view class="orderCopy">
      <text>订单编号：{{orderDetailList.order_sn}}</text>
      <view class="fuzhi" @tap="copyOrder">复制</view>
      <!-- <image bindtap='copyOrder' src='../../img/copy.png'></image> -->
   </view>
   <view v-if="iskan != 1">下单时间：{{orderDetailList.createtime}}</view>
   <view v-if="iskan == 1">下单时间：{{orderDetailList.add_time}}</view>
   <view>支付方式：{{payMode}}</view>
</view>
<view class="bot-btn" v-if="iskan != 1">
   <!-- 待支付 -->
   <view class="fr" v-if="orderDetailList.status==10">
      <view class="btn-cancel" @tap="showCloseOrder">取消订单</view>
      <view @tap="toPay" class="btn-pay">去支付</view>
   </view>
   <!-- 待发货 -->
   <view class="fr" v-if="orderDetailList.status==11">
      <view>
         <text style="font-size:36rpx;color:#e51f54">该订单已支付</text>
         <!-- <view bindtap='afterSale' class='btn-pay'>申请售后</view> -->
      </view>
   </view>
   <!-- 待收货 -->
   <view class="fr" v-if="orderDetailList.status==6">
      <!-- <view class='btn-cancel' bindtap='showCloseOrder'>取消订单</view> -->
      <view @tap="toGetShop" class="btn-pay">确认收货</view>
         <view @tap="afterSale" class="btn-pay">申请售后</view>
   </view>
   <!-- 待评价 -->
   <view class="fr" v-if="orderDetailList.status==8">
      <!-- <view class='btn-cancel' bindtap='showCloseOrder'>取消订单</view> -->
      <!-- <view bindtap='toAppRaise' class='btn-pay'>去评价</view> -->
      <view>
         <text style="font-size:36rpx;color:#e51f54">已收货，等待评价</text>
         <view @tap="afterSale" class="btn-pay">申请售后</view>
      </view>
   </view>
   <!-- 已完成 -->
   <view class="fr" v-if="orderDetailList.status==4">
      <view>
         <text style="font-size:36rpx;color:#e51f54">已完成</text>
         <view @tap="afterSale" class="btn-pay">申请售后</view>
      </view>
   </view>
</view>
<view class="bot-btn" v-if="iskan == 1">
   <!-- 待支付 -->
   <view class="fr" v-if="orderDetailList.status==1">
      <view class="btn-cancel" @tap="quxiao">取消订单</view>
      <view @tap="toPay" class="btn-pay">去支付</view>
   </view>
   <!-- 待发货 -->
   <view class="fr" v-if="orderDetailList.status==2">
      <view>
         <text style="font-size:36rpx;color:#e51f54">该订单待发货</text>
      </view>
   </view>
   <!-- 待收货 -->
   <view class="fr" v-if="orderDetailList.status==4">
      <!-- <view class='btn-cancel' bindtap='showCloseOrder'>取消订单</view> -->
      <view @tap="queren" class="btn-pay">确认收货</view>
   </view>
   <!-- 待评价 -->
   <view class="fr" v-if="orderDetailList.status==5">
      <!-- <view class='btn-cancel' bindtap='showCloseOrder'>取消订单</view> -->
      <!-- <view bindtap='toAppRaise' class='btn-pay'>去评价</view> -->
      <view>
         <text style="font-size:36rpx;color:#e51f54">已完成</text>
      </view>
   </view>
   <!-- 已取消 -->
   <view class="fr" v-if="orderDetailList.status==9">
      <!-- <view class='btn-cancel' bindtap='showCloseOrder'>取消订单</view> -->
      <!-- <view bindtap='toAppRaise' class='btn-pay'>去评价</view> -->
      <view>
         <text style="font-size:36rpx;color:#e51f54">订单已经取消</text>
      </view>
   </view>
</view>
<!-- 取消订单 -->
<!-- <view wx:if='{{isShow}}' class='closeOrder' bindtap='showCloseOrder'>
  <view class='closeOrder-nav' >
    <radio-group class="radio-group" catchtap="radioChange">
      <label class="radio" >
        <view><radio value="1" checked="true"/>我不想买了</view>
      </label>
      <label class="radio" >
        <view><radio value="2" />信息填写错误.重新拍</view>
        </label>
        <label class="radio" >
        <view><radio value="3" />卖家缺货</view>
        </label>
        <label class="radio" >
        <view><radio value="4" />同城见面交易</view>
        </label>
        <label class="radio" >
        <view><radio value="5" />其他原因<input type="text" placeholder="请输入理由" bindinput='getInputValue'></input></view>
        </label>
    </radio-group>
    <view class='dianji' catchtap='closeOrders'>提交</view>
  </view>
</view> -->
</view>
</template>

<script>
let goodsList = [{
  actEndTime: '2018-11-30 18:00:00'
}];
import api from "../../../api";
var app = getApp();

export default {
  data() {
    return {
      userId: '',
      orderId: '',
      // 取消订单type
      closeOrder: '1',
      // 理由
      reason: '',
      // 取消订单显示/隐藏
      isShow: false,
      // 订单详情
      orderDetailList: '',
      countDownList: [],
      actEndTimeList: [],
      // 支付参数--------------------
      openId: '',
      // 订单编号
      order_sn: '',
      // 支付类型
      payType: 2,
      // 支付金额
      payMoney: '',
      iskan: '',
      order_id: '',
      payMode: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    let openid = wx.getStorageSync("openid");
    let userId = wx.getStorageSync("userId");
    this.setData({
      openId: openid,
      userId: userId,
      orderId: options.order_sn,
      iskan: options.iskan
    });

    if (this.iskan == 1) {
      this.iskanFun();
    } else {
      this.getlist();
    }

    console.log(this.orderId);
    let endTimeList = []; // 将活动的结束时间参数提成一个单独的数组，方便操作

    goodsList.forEach(o => {
      endTimeList.push(o.actEndTime);
    });
    this.setData({
      actEndTimeList: endTimeList
    }); // 执行倒计时函数

    this.countDown();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getlist();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  methods: {
    timeFormat(param) {
      return param < 10 ? '0' + param : param;
    },

    countDown() {
      //倒计时函数
      // 获取当前时间，同时得到活动结束时间数组
      let newTime = new Date().getTime();
      let endTimeList = this.actEndTimeList;
      let countDownArr = []; // 对结束时间进行处理渲染到页面

      endTimeList.forEach(o => {
        let endTime = new Date(o).getTime();
        let obj = null; // 如果活动未结束，对时间进行处理

        if (endTime - newTime > 0) {
          let time = (endTime - newTime) / 1000; // 获取天、时、分、秒

          let day = parseInt(time / (60 * 60 * 24));
          let hou = parseInt(time % (60 * 60 * 24) / 3600) + day * 24;
          let min = parseInt(time % (60 * 60 * 24) % 3600 / 60) + hou * 60;
          let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
          obj = {
            day: this.timeFormat(day),
            hou: this.timeFormat(hou),
            min: this.timeFormat(min),
            sec: this.timeFormat(sec)
          };
        } else {
          //活动已结束，全部设置为'00'
          obj = {
            day: '00',
            hou: '00',
            min: '00',
            sec: '00'
          };
        }

        countDownArr.push(obj);
      }); // 渲染，然后每隔一秒执行一次倒计时函数

      this.setData({
        countDownList: countDownArr
      });
      setTimeout(this.countDown, 1000);
    },

    // 加载数据
    getlist() {
      let that = this;
      app.globalData.request({
        url: api.fyz.orderDetail,
        data: {
          order_sn: that.orderId,
          uid: that.userId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          that.setData({
            orderDetailList: res,
            payMode: res.pay_name
          });
        },
        fail: function (res) {//失败后的逻辑
        }
      });
    },

    //砍价
    iskanFun() {
      let that = this;
      app.globalData.request({
        url: api.default.bargainorder_info,
        data: {
          order_id: this.orderId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          that.setData({
            orderDetailList: res.order_info,
            order_id: res.order_info.order_id
          });
        },
        fail: function (res) {//失败后的逻辑
        }
      });
    },

    //去支付
    toPay: function () {
      this.weixinPayMoney(); // wx.navigateTo({
      //   url: '../../packageA/pay/pay?order=' + this.data.orderDetailList.order_sn + '&type=2&money=' + this.data.orderDetailList.order_amount
      // })
    },

    // 微信支付
    weixinPayMoney() {
      var _that = this; // console.log(_that.data.order)
      // console.log(_that.data.type)
      // console.log(_that.data.payMoney)


      app.globalData.request({
        url: api.fyz.weixinPay,
        data: {
          type: _that.payType,
          pay_sn: _that.orderDetailList.order_sn,
          money: _that.orderDetailList.order_amount,
          openid: _that.openId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res); //  付款成功

          if (res.status == 1) {
            wx.requestPayment({
              appId: res.weixin_config.appid,
              nonceStr: res.weixin_config.nonce_str,
              package: 'prepay_id=' + res.weixin_config.prepay_id,
              signType: 'MD5',
              timeStamp: res.weixin_config.timestamp,
              paySign: res.weixin_config.sign,
              success: function (res1) {
                //  更新订单状态
                app.globalData.request({
                  url: api.fyz.updataOrder,
                  data: {
                    user_id: _that.userId,
                    order_sn: _that.orderDetailList.order_sn,
                    payment_id: 2
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded' // 默认值

                  },
                  method: 'POST',
                  success: res => {
                    console.log(res);

                    if (res.status == 1) {
                      console.log(_that.userId);

                      _that.iskanFun(); // wx.redirectTo({
                      //   url: '../../packageB/order/order?status=0&userId=' + _that.data.userId,
                      // })
                      // wx.removeStorageSync('couponId')

                    } else {
                      wx.showToast({
                        title: '支付失败',
                        icon: 'none',
                        duration: 1000
                      });
                    }
                  }
                });
              },
              fail: function (res2) {
                wx.showToast({
                  title: '支付失败，请重新支付',
                  duration: 1000
                });
              }
            });
          }
        },
        fail: function (ret) {
          console.log(ret);
        },
        complete: function (reb) {
          console.log(reb);
        }
      });
    },

    //确认收货
    toGetShop: function () {
      let that = this;
      wx.showModal({
        content: '您确定要收货吗',
        confirmText: '拿到货物',
        cancelText: '还未拿到',

        success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
            app.globalData.request({
              url: api.fyz.confirmShop,
              data: {
                uid: that.userId,
                order_id: that.orderDetailList.id
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值

              },
              method: 'POST',
              success: res => {
                console.log(res);

                if (res.status == 1) {
                  wx.showToast({
                    title: '收货成功',
                    duration: 1000
                  });
                  setTimeout(function () {
                    that.userOrder();
                  }, 1000);
                }
              },
              fail: function (res) {//失败后的逻辑
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
            return;
          }
        }

      });
    },
    //去评价
    // toAppRaise: function () {
    //   // var id = this.data.goodsID[a]
    //   let amm =['111','222','333']
    //   // console.log(a)
    //   wx.navigateTo({
    //     url: '../../packageA/appraise/appraise?id=' + amm,
    //   })
    // },
    // 选择原因
    radioChange: function (e) {
      this.setData({
        closeOrder: e.detail.value
      });
      console.log(e.detail.value);
    },
    // 取消订单
    showCloseOrder: function () {
      let that = this;
      wx.showModal({
        title: '提示',
        content: '订单还未付款，确定要取消吗',
        cancelText: '取消订单',
        confirmText: '再考虑下',

        success(res) {
          if (res.confirm) {
            return;
          } else if (res.cancel) {
            app.globalData.request({
              url: api.fyz.delOrder,
              data: {
                order_id: that.orderDetailList.id,
                uid: that.userId,
                reason_id: 1
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值

              },
              method: 'POST',
              success: res => {
                console.log(res);

                if (res.status == 1) {
                  wx.showToast({
                    title: res.data.msg,
                    duration: 1000
                  });
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '../../packageB/order/order?status=0&userId=' + that.userId
                    });
                  }, 1000);
                }
              },
              fail: function (res) {//失败后的逻辑
              }
            });
          }
        }

      }); // this.setData({
      //   isShow:!that.data.isShow
      // })
    },
    //砍价
    // 去支付
    toPay: function (e) {
      console.log(e.currentTarget.dataset.index);
      let index = e.currentTarget.dataset.index;
      this.setData({
        order_sn: this.orderDetailList.order_sn,
        payMoney: this.orderDetailList.total_price,
        order_id: this.orderDetailList.order_id
      }); // 吊起微信支付

      this.weixinPayMoney(); // wx.navigateTo({
      //   url: '../../packageA/pay/pay?order=' + this.data.orderList[index].order_sn + '&type=2&money=' + this.data.orderList[index].total_price + '&userId=' + this.data.userId
      // })
    },

    // 微信支付
    weixinPayMoney() {
      var _that = this; // console.log(_that.data.order)
      // console.log(_that.data.type)
      // console.log(_that.data.payMoney)


      app.globalData.request({
        url: api.fyz.weixinPay,
        data: {
          type: 5,
          pay_sn: _that.orderDetailList.order_sn,
          money: _that.payMoney,
          openid: _that.openId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          var prepayid = res.ioswx_config.prepayid,
              osn = res.osn;
          console.log('支付id:', prepayid); //  付款成功

          if (res.status == 1) {
            wx.requestPayment({
              appId: res.weixin_config.appid,
              nonceStr: res.weixin_config.nonce_str,
              package: 'prepay_id=' + res.weixin_config.prepay_id,
              signType: 'MD5',
              timeStamp: res.weixin_config.timestamp,
              paySign: res.weixin_config.sign,
              success: function (res1) {
                wx.getStorage({
                  key: 'userId',
                  success: function (aaa) {
                    console.log(aaa.data);
                    var open = aaa.data;
                    console.log(open);
                    app.globalData.request({
                      url: api.gzSea.message,
                      //仅为示例，并非真实的接口地址
                      data: {
                        sole: prepayid,
                        order_sn: osn,
                        user_id: open
                      },
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded' // 默认值

                      },

                      success(res) {
                        console.log(res);
                      }

                    });
                  }
                }); //  更新订单状态

                app.globalData.request({
                  url: api.default.bargainorder_update_pay,
                  data: {
                    order_id: _that.order_id
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded' // 默认值

                  },
                  method: 'POST',
                  success: res => {
                    console.log(res);

                    if (res.status == 1) {
                      console.log(_that.userId);

                      _that.iskanFun(); // wx.redirectTo({
                      //   url: '../../packageB/order/order?status=0&userId=' + _that.data.userId,
                      // })
                      // wx.removeStorageSync('couponId')

                    } else {
                      wx.showToast({
                        title: res.msg,
                        duration: 1000
                      });
                    }
                  }
                });
              },
              fail: function (res2) {
                wx.showToast({
                  title: '支付失败，请重新支付',
                  icon: 'none',
                  duration: 1000
                });
              }
            });
          }
        },
        fail: function (ret) {
          console.log(ret);
        },
        complete: function (reb) {
          console.log(reb);
        }
      });
    },

    //确认收货
    queren: function (e) {
      var that = this;
      console.log(e.currentTarget.dataset.index);
      wx.showModal({
        content: '您确定要收货吗？',

        success(res) {
          if (res.confirm) {
            app.globalData.request({
              url: api.default.bargaincollect_order,
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 'content-type': 'application/json'

              },
              data: {
                order_id: that.order_id
              },
              method: 'POST',
              success: res => {
                that.iskanFun();
                wx.showToast({
                  title: res.msg,
                  icon: 'none'
                });
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }

      });
    },
    //取消订单
    quxiao: function (e) {
      var that = this;
      console.log(e.currentTarget.dataset.index);
      wx.showModal({
        title: '提示',
        content: '订单还未付款，确定要取消吗？',

        success(res) {
          if (res.confirm) {
            app.globalData.request({
              url: api.default.bargaincancel_order,
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 'content-type': 'application/json'

              },
              data: {
                order_id: that.order_id
              },
              method: 'POST',
              success: res => {
                that.iskanFun();
                wx.showToast({
                  title: res.msg,
                  icon: 'none'
                });
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }

      });
    },
    //砍价结束
    // 获取取消订单理由
    getInputValue: function (e) {
      console.log(e.detail.value);
      this.setData({
        reason: e.detail.value
      });
    },

    // 复制订单号
    copyOrder() {
      wx.setClipboardData({
        data: this.orderDetailList.order_sn,

        success(res) {
          console.log(res);
          wx.showToast({
            title: '复制成功',
            icon: 'none'
          });
        }

      });
    },

    //申请售后页
    afterSale: function () {
      wx.navigateTo({
        url: '../../packageB/replace/replace?order_sn=' + this.orderId + '&uid=' + this.userId
      });
    }
  }
};
</script>
<style>
@import "./orderdetail.css";
</style>